//
//  JokeViewController.m
//  miaopai
//
//  Created by Crow Zhang on 15/11/12.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "JokeViewController.h"
#import "MacroDefinition.h"
#import "JokeCollectionViewCell.h"
#import "DEFINE.h"
#import "CoreData.h"
#import "CustomerNetworking.h"
#import "LastJoking+CoreDataProperties.h"
#import <MJRefresh.h>
#import "SomeJoke+CoreDataProperties.h"
#import "UMSocial.h"

@interface JokeViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain) CoreData *coreData; // coreData

@property (nonatomic, retain) UISegmentedControl *segment;

/****************************第一个 collectionview 数组, 等 **************/
@property(nonatomic, retain) UICollectionView *lastCollectionView; // collectionView

@property (nonatomic, retain) NSMutableArray * lastCollectionArr; // array

@property (nonatomic, retain) MJRefreshNormalHeader *lastHeader; // 下拉刷新

@property (nonatomic, retain) MJRefreshAutoNormalFooter *lastFooter; // 上拉加载

@property (nonatomic, retain) UIView *lastView; // 最新段子背景
/***************************第二个 collectionview 数组, 等**********/

@property (nonatomic, retain) UICollectionView *someCollectionView; // 随机段子

@property (nonatomic, retain) NSMutableArray *someCollectionArr; // array

@property (nonatomic, retain) MJRefreshNormalHeader *someHeader; // 下拉刷新

@property (nonatomic, retain) MJRefreshAutoNormalFooter *someFooter; // 上啦加载

@property (nonatomic, retain) UIView *someView; // 第二个页面
@end

@implementation JokeViewController


- (void)dealloc
{
    [_someCollectionView release];
    [_someCollectionArr release];
    [_someHeader release];
    [_someFooter release];
    [_someView release];
    [_segment release];
    [_lastFooter release];
    [_lastHeader release];
    [_lastCollectionArr release];
    [_lastCollectionView release];
    [_lastView release];
    [_coreData release];
    [super dealloc];
}


/**************************************初始化以及数据解析*************************************/
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.coreData = [CoreData shareManagerWithFile:@"joke"];
        NSLog(@"%@", _coreData.applicationDocumentsDirectory);
        /************************第一个页面数据**************/
        self.lastHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadData)];
        self.lastFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
        self.lastCollectionArr = [NSMutableArray array];
        [self getData];
        /***************************第二个页面数据***************/
        self.someHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadSomeData)];
        self.someFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadSomeData)];
        self.someCollectionArr = [NSMutableArray array];
        [self getSomeData];
    }
    return self;
}

#pragma 进入页面将要数据重新请求
- (void)viewWillAppear:(BOOL)animated{
    [self reloadData];
    [self reloadSomeData];
}

#pragma 刷新页面 请求数据
- (void)reloadData{ // 页面1
    i = 2;
    [self getData];
}
- (void)reloadSomeData{ // 页面2
    j = 2;
    [self getSomeData];
}
#pragma 加载页面 请求数据
static NSInteger i = 2; // 页面1
static NSInteger j = 2; // 页面2
- (void)loadData{ // 页面 1
    [CustomerNetworking customerConnectWithURL:[NSString stringWithFormat:@"http://joke.luckyamy.com/api/?cat=dz&p=%ld&ap=ymds&ver=1.6", (long)++i] andparameters:nil andBlock:^(id response) {

        for (NSDictionary *dic in response) {
            LastJoking *joke = [NSEntityDescription insertNewObjectForEntityForName:@"LastJoking" inManagedObjectContext:_coreData.managedObjectContext];
            joke.text = [dic objectForKey:@"text"];
            joke.created_at = [dic objectForKey:@"created_at"];
            NSString *string = [NSString stringWithFormat:@"%@",[dic objectForKey:@"zan"]];
            joke.zan = string;
            [self.lastCollectionArr addObject:joke];
        }
        [self.lastFooter endRefreshing];
        [self.lastCollectionView reloadData];

    }];
}

- (void)loadSomeData{ // 页面 2
    [CustomerNetworking customerConnectWithURL:[NSString stringWithFormat:@"http://joke.luckyamy.com/api/?cat=dz&type=random&p=%ld&time=1432968548&ap=ymds&ver=1.6", ++i] andparameters:nil andBlock:^(id response) {

        for (NSDictionary *dic in response) {
            SomeJoke *joke = [NSEntityDescription insertNewObjectForEntityForName:@"SomeJoke" inManagedObjectContext:_coreData.managedObjectContext];
            joke.text = [dic objectForKey:@"text"];
            joke.created_at = [dic objectForKey:@"created_at"];
            NSString *string = [NSString stringWithFormat:@"%@",[dic objectForKey:@"zan"]];
            joke.zan = string;
            [self.someCollectionArr addObject:joke];
        }
        [self.someFooter endRefreshing];
        [self.someCollectionView reloadData];
    }];
}

- (void)searchLastJokingData { // 页面1
    //        给 array 赋值
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"LastJoking"];
    [request setReturnsObjectsAsFaults:NO];
    NSArray *arr = [_coreData.managedObjectContext executeFetchRequest:request error:nil];
    if (arr.count != 0) {
        for (LastJoking *joke in arr) {
            [self.lastCollectionArr addObject:joke];
        }
    }
}

- (void)searchSomeJokingData { // 页面2
    //        给 array 赋值
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"SomeJoke"];
    [request setReturnsObjectsAsFaults:NO];
    NSArray *arr = [_coreData.managedObjectContext executeFetchRequest:request error:nil];
    if (arr.count != 0) {
        for (SomeJoke *joke in arr) {
            [self.someCollectionArr addObject:joke];
        }
    }

}


#pragma 数据请求分为几个部分执行, 进入页面, 以及下拉时
- (void)getData{  // 页面1

    [self searchLastJokingData];
    
    [CustomerNetworking customerConnectWithURL:JOKING_FIRST andparameters:nil andBlock:^(id response) {
        //        网络请求 判断是否有本地数据, 如果有, 赋值给数组, 没有, 存到数据库 并且赋值
        for (LastJoking *joke in _lastCollectionArr) {
            [_coreData.managedObjectContext deleteObject:joke];
        }
        [self.lastCollectionArr removeAllObjects];

        for (NSDictionary *dic in response) {
            LastJoking *joke = [NSEntityDescription insertNewObjectForEntityForName:@"LastJoking" inManagedObjectContext:_coreData.managedObjectContext];
            joke.text = [dic objectForKey:@"text"];
            joke.created_at = [dic objectForKey:@"created_at"];
            NSString *string = [NSString stringWithFormat:@"%@",[dic objectForKey:@"zan"]];
            joke.zan = string;
            [_coreData saveContext];
        }
        [self.lastHeader endRefreshing];
        [self searchLastJokingData];
        [self.lastCollectionView reloadData];
        
    }];
}
- (void)getSomeData{  // 页面2

    [self searchSomeJokingData];

    [CustomerNetworking customerConnectWithURL:JOKING_SECOND andparameters:nil andBlock:^(id response) {
        //        网络请求 判断是否有本地数据, 如果有, 赋值给数组, 没有, 存到数据库 并且赋值



        for (SomeJoke *joke in _someCollectionArr) {
            [_coreData.managedObjectContext deleteObject:joke];
        }
        [self.someCollectionArr removeAllObjects];

        for (NSDictionary *dic in response) {
            SomeJoke *joke = [NSEntityDescription insertNewObjectForEntityForName:@"SomeJoke" inManagedObjectContext:_coreData.managedObjectContext];
            joke.text = [dic objectForKey:@"text"];
            joke.created_at = [dic objectForKey:@"created_at"];
            NSString *string = [NSString stringWithFormat:@"%@",[dic objectForKey:@"zan"]];
            joke.zan = string;
            [_coreData saveContext];
        }
        [self.someHeader endRefreshing];
        [self searchSomeJokingData];
        [self.someCollectionView reloadData];

    }];
}
/******************************************视图加载*******************************************/
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    self.title = @"段子";
    // Do any additional setup after loading the view.
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = backItem;
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    //    创建视图
    [self creatViews];

}

- (void)back:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma segment 值改变事件
- (void)segmentChange:(UISegmentedControl *)segment{
    if (segment.selectedSegmentIndex == 0) {
        [self.view insertSubview:_lastView aboveSubview:_someView];
        return;
    }
    [self.view insertSubview:_someView aboveSubview:_lastView];
}

#pragma mark - 创建视图
#pragma mark 创建 collectionView
- (void)creatViews{

/****************************************segment 视图***************************/
    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"最新段子", @"随机穿越"]];
    self.segment.selectedSegmentIndex = 0;
    [self.segment addTarget:self action:@selector(segmentChange:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = self.segment;
    [_segment release];


/******************************第二个页面***************************/
    self.someView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    _someView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_someView];
    [_someView release];

    UICollectionViewFlowLayout *someCollectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];

    someCollectionViewFlowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);

    //    设置单元滑动方向
    someCollectionViewFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;

    //    如果没有 tabbar 的话需要把高度再减44
    self.someCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, _someView.Width, _someView.Height) collectionViewLayout:someCollectionViewFlowLayout];
    self.someCollectionView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:0.5];
    self.someCollectionView.delegate = self;
    self.someCollectionView.dataSource = self;
    self.someCollectionView.mj_header = self.someHeader;
    self.someCollectionView.mj_footer = self.someFooter;
    [_someView addSubview:_someCollectionView];
    [_someCollectionView release];
    [someCollectionViewFlowLayout release];

    [self.someCollectionView registerClass:[JokeCollectionViewCell class] forCellWithReuseIdentifier:@"someCollectionViewCell"];


/******************************第一个页面****************************/

    self.lastView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    self.lastView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.lastView];
    [_lastView release];

    UICollectionViewFlowLayout *collectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];

    collectionViewFlowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);

    //    设置单元滑动方向
    collectionViewFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;

    //    如果没有 tabbar 的话需要把高度再减44
    self.lastCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, _lastView.Width, _lastView.Height) collectionViewLayout:collectionViewFlowLayout];
    self.lastCollectionView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:0.5];
    self.lastCollectionView.delegate = self;
    self.lastCollectionView.dataSource = self;
    self.lastCollectionView.mj_header = self.lastHeader;
    self.lastCollectionView.mj_footer = self.lastFooter;
    [_lastView addSubview:_lastCollectionView];
    [_lastCollectionView release];
    [collectionViewFlowLayout release];

    [self.lastCollectionView registerClass:[JokeCollectionViewCell class] forCellWithReuseIdentifier:@"collectionViewCell"];
}

#pragma mark - 协议
#pragma mark collectionView 的协议

#pragma mark 自适应高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    CGFloat vHeight = SCREEN_HEIGHT / 20;

    if (collectionView == _someCollectionView) {
        SomeJoke *joke = [self.someCollectionArr objectAtIndex:indexPath.item];
        CGFloat height = [JokeCollectionViewCell heightOfText:joke.text];
    CGSize size = CGSizeMake(SCREEN_WIDTH - 20, height + 2 * vHeight + 10);
        return size;
    }
    LastJoking *joke = [self.lastCollectionArr objectAtIndex:indexPath.item];
    CGFloat height = [JokeCollectionViewCell heightOfText:joke.text];
    CGSize size = CGSizeMake(SCREEN_WIDTH - 20, height + 2 * vHeight + 10);
    return size;
}
#pragma mark 行数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == _someCollectionView) {
        return self.someCollectionArr.count;
    }
    return self.lastCollectionArr.count;
}
#pragma mark 详情
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _someCollectionView) {
        JokeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"someCollectionViewCell" forIndexPath:indexPath];
        [cell setBackgroundColor:[UIColor whiteColor]];
        cell.someJoke = [self.someCollectionArr objectAtIndex:indexPath.item];
        [cell shareButtonClicked:^{
//            [UMSocialSnsService presentSnsController:self appKey:@"565415bfe0f55aaf68000909" shareText:@"" shareImage:@"" shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,nil] delegate:NULL];
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:@"56554e9967e58e6ff800226b"
                                              shareText:cell.someJoke.text
                                             shareImage:nil
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,UMShareToTencent,nil]
                                               delegate:nil];
        }];
        return cell;
    }

    JokeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionViewCell" forIndexPath:indexPath];
    [cell setBackgroundColor:[UIColor whiteColor]];
    cell.myJoke = [self.lastCollectionArr objectAtIndex:indexPath.item];
    [cell shareButtonClicked:^{
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"56554e9967e58e6ff800226b"
                                          shareText:cell.myJoke.text
                                         shareImage:nil
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,UMShareToTencent,nil]
                                           delegate:nil];
    }];
    return cell;
}


@end
